package com.surfilter.msmp.common.util.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 * 监控非活跃连接
 * @author well
 * @version 4.1
 */
public class IdleConnectionMonitorThread extends Thread {

	private static Logger logger = LoggerFactory.getLogger(IdleConnectionMonitorThread.class);
	
	private final HttpClientConnectionManager cm;

	private volatile boolean shutdown;

	public IdleConnectionMonitorThread(HttpClientConnectionManager cm) {
		super();
		this.cm = cm;
	}

	@Override
	public void run() {
		try {
			while (!shutdown) {
				synchronized (this) {
					wait(10000);
					// 关闭失效的连接
					cm.closeExpiredConnections();
					// 可选的, 关闭30秒内不活动的连接
					cm.closeIdleConnections(3, TimeUnit.SECONDS);
				}
			}
		} catch (InterruptedException e) {
			logger.warn("监控非活跃连接线程异常中断");
		}
	}
	
	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
	
}
